import axios from 'axios'
import {Message} from 'element-ui'
import Qs from 'qs'




const getService = (opts = {}) => {
  // 创建axios实例

  let options = {
    baseURL: process.env.BASE_API, // api的base_url
    timeout: 5000
  }


  if (opts.payload) {


  } else {



    options.transformRequest = [function (data) {
      data = Qs.stringify(data);
      return data;
    }]

  }


  var service = axios.create(options)

  service.interceptors.request.use(config => {

    if (!config.params) {
      config.params = {}
    }


    config.params.responseType = 'json'

    if (opts.payload) {

      config.data = parseData(config.data);

    }



    return config
  }, error => {
    console.log(error)
    Promise.reject(error)
  })

  service.interceptors.response.use(
    response => {

      const res = response.data


      // if (res.status != 200) {
      //   Message({
      //     message: res.message,
      //     type: 'error',
      //     duration: 5 * 1000
      //   })

      //   return Promise.reject('error')
      // } else {
      //   return response.data
      // }


      return response.data;

    },
    error => {
      // console.log('err' + error)
      // Message({
      //   message: error.message,
      //   type: 'error',
      //   duration: 5 * 1000
      // })
      // return Promise.reject(error)
    }
  )


  return service;

}


function parseData(data) {


  if (typeof data == 'object') {

    var str = JSON.stringify(data)

    if (str.indexOf('.000Z') > 0) {

      str = str.replace(/\.000Z/g, '').replace(/(\d+)T(\d+)/g, '$1 $2')
      return JSON.parse(str)
    }


  }


  return data

}

export default {

  postPayload: (url, data) => {
    var fetch = getService({payload: true})

    return fetch({
      url: url,
      method: 'post',
      data: data
    })
  },
  post: (url, data) => {


    var fetch = getService()


    return fetch({
      url: url,
      method: 'post',
      data: data
    })
  },
  get: (url, params) => {
    var fetch = getService()


    return fetch({
      url: url,
      method: 'get',

      params: params
    })
  }
}
